package dao

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"petCombo-srv/global"
	"petCombo-srv/internal/model"
)

type OrderImpl interface {
}
type OrderService struct {
}

func NewOrderService() *OrderService {
	return &OrderService{}
}
func (o *OrderService) Order(orderMsg model.Order) error {

	key := fmt.Sprintf("order:%d", orderMsg.UserId)

	result, _ := global.Rdb.Exists(context.Background(), key).Result()
	if result != 0 {
		return errors.New("不能重复下单")
	}

	marshal, err := json.Marshal(orderMsg)
	if err != nil {
		return err
	}

	keyNumber := fmt.Sprintf("order_num:%d", orderMsg.ComboId)

	Number, _ := global.Rdb.RPop(context.Background(), keyNumber).Result()

	if Number <= "0" {
		return errors.New("没有库存")
	}

	err = global.Rdb.Set(context.Background(), key, marshal, 0).Err()
	if err != nil {
		return errors.New("redis下单 生成失败:" + err.Error())
	}

	return nil
}
